import concurrent.futures
import cv2
import os
import numpy as np


def process_image(count, name, i, sli, base_name, amount, base):
    if count < i:
        return None
    elif count > (sli + i):
        return None
    else:
        if base_name == "startrails":
            base_name = os.path.splitext(name)[0].lower()
        if os.path.splitext(name)[1].lower() == '.jpg':
            percentage = (count - i) / amount * 100
            path = os.path.join(base, name)
            curr = cv2.imread(path)
            alpha = (count - i) / amount
            curr = curr * (1 - alpha)
            return curr


sli = 100
start_index = 308
result_path = "test/"
base_name = "startrails"
extension = ".jpg"
base = 'G:\\MyFile\\sky\\721Lr'
names = sorted(os.listdir(base))

amount = sli
frame = None

with concurrent.futures.ThreadPoolExecutor() as executor:
    def save_frame(frame, base_name, i, result_path):
        result_name = base_name + extension
        cv2.imwrite(os.path.join(result_path, result_name), frame)


    for i in range(start_index, 1290):
        futures = []
        for count, name in enumerate(names):
            if len(futures) >= sli:
                break
            futures.append(executor.submit(process_image, count, name, i, sli, base_name, amount, base))

        for future in concurrent.futures.as_completed(futures):
            curr = future.result()
            if curr is not None:
                if frame is None:
                    frame = curr
                else:
                    frame = np.maximum(frame, curr)

        save_frame(frame, base_name, i, result_path)
        base_name = "startrails"
        frame = None
